#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*	selection_sort.cpp
*	This program is part of the °Simple-Benchs° Benchmark
*	The complexity of this program is O(n²) where n is the list's size
*
*	
*	To run the program:	./program array_size max_element
*/

/* Array initialization. Complexity O(n) where n is the array's size*/
void initArray(int* vet, int size, int max_num) {
  int count = 0;
  for (count = 0; count < size; count++) {
    vet[count] = rand() % max_num;
  }
}

/* Program standart output. Display a list (array of elements).  Complexity O(n) where n is the array's size */
void printArray(int* vet, int size) {
  int count = 0;
  for (count = 0; count < size; count++) {
    printf("%d ", vet[count]);
  }
  printf("\n");
}

/*	Perform the sort by the Selection Sort algorithm. Complexity O(n²) defined by the nested loops starting the line 34, 
where n is size of the list */
void selectionSort(int *vet, int size) {
  int count, aux, position, swap;
  for ( count = 0 ; count < ( size - 1 ) ; count++ ) {
    position = count; 
    for ( aux = count + 1 ; aux < size ; aux++ ) {
      if (vet[position] > vet[aux])
        position = aux;
    }
    if ( position != count ) {
      swap = vet[count];
      vet[count] = vet[position];
      vet[position] = swap;
    }
   }
}

/*	Initial check to verify whether the amount of arguments is correct or not.  Complexity O(1)	*/
short Initial_check(int inputs){
  if (inputs != 3) {
  	fprintf(stderr, "Syntax: ./program size max_num\n");
    return 1;
  }
  return 0;
}


int main(int argc, char** argv) {

	/* Checking arguments */
  if (Initial_check(argc)) return 1;

  /* Retrieve problem size. */
  int size = atoi(argv[1]);
  int max_num = atoi(argv[2]);

  /* Seed initialization. */
  srand((unsigned)time(NULL));

	/* Variable declaration/allocation/initialization. */
  int* vet = (int*) malloc(size * sizeof(int));  
  initArray(vet, size, max_num);

  /* Display the input*/  	
  printArray(vet, size);

	/* Sorting */
  selectionSort(vet, size);

  /* Display the result*/  	
  printArray(vet, size);

  /* Be clean. */
  free(vet);
}
